package shell.command;

import java.io.PrintStream;

/**
 * Commande d'aide.
 * 
 * @version 1.0
 */
public final class HelpCommandImpl extends ShellCommandImpl {
    /**
     * Constructeur.
     * 
     * @param context
     *            Contexte d'exécution.
     */
    public HelpCommandImpl(final ShellContext context) {
	super(context);
    }

    /**
     * @see shell.command.ShellCommand#getName().
     */
    public String getName() {
	return "help";
    }

    /**
     * @see shell.command.ShellCommand#getUsage().
     */
    public String getUsage() {
	return "help";
    }

    /**
     * @see shell.command.ShellCommand#getShortDescription().
     */
    public String getShortDescription() {
	return "Display shell commands";
    }

    /**
     * @see shell.command.ShellCommand#execute(String, PrintStream, PrintStream)
     *      .
     */
    public void execute(final String s, final PrintStream out,
	    final PrintStream err) {
	try {
	    ShellCommand[] cmds = super.getContexte().getCommands();
	    String[] usage = new String[cmds.length];
	    String[] desc = new String[cmds.length];
	    int maxUsage = 0;
	    for (int i = 0; i < cmds.length; i++) {
		usage[i] = cmds[i].getUsage();
		desc[i] = cmds[i].getShortDescription();
		// Just in case the command has gone away.
		if ((usage[i] != null) && (desc[i] != null)) {
		    maxUsage = Math.max(maxUsage, usage[i].length());
		}
	    }
	    StringBuffer sb = new StringBuffer();
	    for (int i = 0; i < cmds.length; i++) {
		// Just in case the command has gone away.
		if ((usage[i] != null) && (desc[i] != null)) {
		    sb.delete(0, sb.length());
		    for (int j = 0; j < (maxUsage - usage[i].length()); j++) {
			sb.append(' ');
		    }
		    out.println(usage[i] + sb + " - " + desc[i]);
		}
	    }

	} catch (final Exception e) {
	    err.println(e.toString());
	}
    }
}
